//
//  EWHMainViewController.m
//  PhnixHome
//
//  Created by Levy Xu on 2017/11/25.
//  Copyright © 2017年 Levy Xu. All rights reserved.
//

#import "EWHMainViewController.h"
#import "PHTimingViewController.h"
#import "PHElectricityViewController.h"
#import "EWHView.h"

@interface EWHMainViewController ()<EWHViewDelegate>
@property(nonatomic, strong) PHDevice *model;

@property(nonatomic, strong) QMUIButton *economyBtn;
@property(nonatomic, strong) QMUIButton *fastBtn;
@property(nonatomic, strong) QMUIButton *powerBtn;
@property(nonatomic, strong) QMUIButton *clockBtn;
@property(nonatomic, strong) QMUIButton *deinfectionBtn;
@property(nonatomic, strong) EWHView *ewhView;

@property(nonatomic, strong) QMUILabel *timingLabel1;
@property(nonatomic, strong) QMUILabel *timingLabel2;

@property(nonatomic, strong) CALayer *separatorLayer;

@property(nonatomic, strong) QMUILabel *monthTitleLabel;
@property(nonatomic, strong) QMUILabel *monthLabel;
@property(nonatomic, strong) QMUILabel *monthUnitLabel;

@property(nonatomic, strong) QMUILabel *dayTitleLabel;
@property(nonatomic, strong) QMUILabel *dayLabel;
@property(nonatomic, strong) QMUILabel *dayUnitLabel;

@property(nonatomic, assign) BOOL serviceAlertHidden;
@property(nonatomic, strong) QMUIAlertController *serviceAlert;
@end

@implementation EWHMainViewController

-(void)dealloc {
    [NNCDC removeObserver:self];
}

- (instancetype)initWithDeviceModel:(PHDevice *)model {
    self = [super init];
    if (self) {
        _model = model;
        [NNCDC addObserver:self selector:@selector(statusChanged:) name:kDeviceStatusChangedNotification object:nil];
    }
    return self;
}

- (void)initSubviews {
    [super initSubviews];
    
    _ewhView = [[EWHView alloc] init];
    _ewhView.delegate = self;
    [self.myView addSubview:_ewhView];
    
    //定时
    _timingLabel1 = [[QMUILabel alloc] init];
    _timingLabel1.font = KKFontMake(18);
    _timingLabel1.textColor = UIColorGray3;
    _timingLabel1.adjustsFontSizeToFitWidth = YES;
    _timingLabel1.textAlignment = NSTextAlignmentCenter;
    [self.myView addSubview:_timingLabel1];
    
    _timingLabel2 = [[QMUILabel alloc] init];
    [_timingLabel2 qmui_setTheSameAppearanceAsLabel:_timingLabel1];
    [self.myView addSubview:_timingLabel2];
    
    _separatorLayer = [CALayer layer];
    [_separatorLayer qmui_removeDefaultAnimations];
    _separatorLayer.backgroundColor = UIColorGray6.CGColor;
    _separatorLayer.cornerRadius = 1.0f;
    [self.myView.layer addSublayer:_separatorLayer];
    
    //电量统计
    _monthTitleLabel = [[QMUILabel alloc] init];
    _monthTitleLabel.font = KKFontMake(16);
    _monthTitleLabel.textColor = UIColorGray5;
    _monthTitleLabel.textAlignment = NSTextAlignmentCenter;
    _monthTitleLabel.text = NSLocalizedString(@"dev_state_month_total_power", nil);
    [self.myView addSubview:_monthTitleLabel];
    
    _monthLabel = [[QMUILabel alloc] init];
    _monthLabel.font = KKFontMake(32);
    _monthLabel.textColor = GQDThemeManager.currentTheme.themeTintColor;
    _monthLabel.textAlignment = NSTextAlignmentCenter;
    _monthLabel.adjustsFontSizeToFitWidth = YES;
    _monthLabel.text = @"0.0";
    [self.myView addSubview:_monthLabel];
    
    _monthUnitLabel = [[QMUILabel alloc] qmui_initWithSize:CGSizeMake(100, 20)];
    _monthUnitLabel.font = KKFontMake(14);
    _monthUnitLabel.textColor = GQDThemeManager.currentTheme.themeTintColor;
    _monthUnitLabel.adjustsFontSizeToFitWidth = YES;
    _monthUnitLabel.text = NSLocalizedString(@"degree", nil);
    [_monthLabel sizeToFit];
    [self.myView addSubview:_monthUnitLabel];
    
    
    _dayTitleLabel = [[QMUILabel alloc] init];
    [_dayTitleLabel qmui_setTheSameAppearanceAsLabel:_monthTitleLabel];
    _dayTitleLabel.text = NSLocalizedString(@"dev_total_time", nil);
    [self.myView addSubview:_dayTitleLabel];
    
    _dayLabel = [[QMUILabel alloc] init];
    [_dayLabel qmui_setTheSameAppearanceAsLabel:_monthLabel];
    _dayLabel.text = @"0";
    [self.myView addSubview:_dayLabel];
    
    _dayUnitLabel = [[QMUILabel alloc] qmui_initWithSize:CGSizeMake(100, 20)];
    [_dayUnitLabel qmui_setTheSameAppearanceAsLabel:_monthUnitLabel];
    _dayUnitLabel.text = NSLocalizedString(@"unit_hour", nil);
    [_dayUnitLabel sizeToFit];
    [self.myView addSubview:_dayUnitLabel];
    
    //底部按钮
    _economyBtn = [self buttonWithImage:@"icon_economy" title:NSLocalizedString(@"dev_mode_eco", nil) action:@selector(economyAction:)];
    [self.view addSubview:_economyBtn];
    
    _fastBtn = [self buttonWithImage:@"icon_fast" title:NSLocalizedString(@"dev_mode_fast_hot", nil) action:@selector(fastAction:)];
    [self.view addSubview:_fastBtn];
    
    _powerBtn = [self buttonWithImage:@"icon_power" title:NSLocalizedString(@"dev_action_power", nil) action:@selector(powerAction:)];
    [self.view addSubview:_powerBtn];
    
    _clockBtn = [self buttonWithImage:@"icon_clock" title:NSLocalizedString(@"dev_action_reservation", nil) action:@selector(clockAction:)];
    [self.view addSubview:_clockBtn];
    
    _deinfectionBtn = [self buttonWithImage:@"icon_deinfection" title:NSLocalizedString(@"dev_action_disinfection", nil) action:@selector(deinfectionAction:)];
    [self.view addSubview:_deinfectionBtn];
}

-(QMUIButton *)buttonWithImage:(NSString *)image title:(NSString *)title action:(SEL)action {
    UIImage *normalImage = UIImageMake(image);
    if (IS_35INCH_SCREEN) {
        normalImage = [normalImage qmui_imageResizedInLimitedSize:CGSizeMake(40, 40)];
    }
    UIImage *selectedImage = [normalImage imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
    
    QMUIButton *button = [[QMUIButton alloc] init];
    button.adjustsButtonWhenHighlighted = YES;
    [button setImage:normalImage forState:UIControlStateNormal];
    [button setImage:selectedImage forState:UIControlStateSelected];
    [button addTarget:self action:action forControlEvents:UIControlEventTouchUpInside];
    if (title) {
        button.titleLabel.font = KKFontMake(14);
        button.imagePosition = QMUIButtonImagePositionTop;
        button.spacingBetweenImageAndTitle = 5.0;
        [button setTitle:title forState:UIControlStateNormal];
        [button setTitleColor:UIColorGray forState:UIControlStateNormal];
        [button setTitleColor:GQDThemeManager.currentTheme.themeCodeColor forState:UIControlStateSelected];
    }
    return button;
}

-(void)showServiceAlert {
    if (_serviceAlertHidden || _serviceAlert) {
        return;
    }
    WS(ws);
    _serviceAlert = [QMUIAlertController alertControllerWithTitle:NSLocalizedString(@"tips_warning", nil)
                                                                       message:@"总运行时间已达到最大值，请联系我们进行检修"
                                                                preferredStyle:QMUIAlertControllerStyleAlert];
    QMUIAlertAction *okAction = [QMUIAlertAction actionWithTitle:NSLocalizedString(@"btn_ok", nil)
                                                           style:QMUIAlertActionStyleDefault
                                                         handler:^(__kindof QMUIAlertController *aAlertController, QMUIAlertAction *action) {
                                                               ws.serviceAlert = nil;
                                                               ws.serviceAlertHidden = YES;
                                                           }];
    [_serviceAlert addAction:okAction];
    
    UIView *contentView = [[UIView alloc] qmui_initWithSize:CGSizeMake(_serviceAlert.alertContentMaximumWidth, 50)];
    QMUIGhostButton *btn = [[QMUIGhostButton alloc] initWithGhostType:QMUIGhostButtonColorRed];
    btn.frame = CGRectMake(20, 0, contentView.qmui_width - 40, 40);
    [btn setTitle:@"客服电话4009400900" forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(serviceCall:) forControlEvents:UIControlEventTouchUpInside];
    [contentView addSubview:btn];
    [_serviceAlert addCustomView:contentView];
    
    [_serviceAlert showWithAnimated:YES];
}

-(void)serviceCall:(id)sender {
    NSURL *url = [NSURL URLWithString:@"tel:4009400900"];
    if ([[UIApplication sharedApplication] canOpenURL:url]) {
        [[UIApplication sharedApplication] openURL:url];
    } else {
        [KKHUD showInfo:@"不支持拨打电话"];
    }
}

- (void)viewDidLayoutSubviews {
    self.shouldShowMyView = YES;
    [super viewDidLayoutSubviews];
    
    CGFloat margin = 20.0f;
    CGFloat wehHeight = 220;
    CGFloat dayHeight = 75;
    CGFloat monthHeight = 30;
    CGFloat buttonHeight = 90.0f;
    CGFloat buttonMargin = 10.0f;
    if (IS_35INCH_SCREEN) {
        margin = 10.0f;
        wehHeight = 150;
        dayHeight = 60;
        monthHeight = 20;
        buttonHeight = 70.0f;
        buttonMargin = 5.0f;
    }
    else if(IS_40INCH_SCREEN) {
        margin = 10.0f;
        wehHeight = 180;
    }
    else if(IS_58INCH_SCREEN) {
        margin = 30.0f;
        wehHeight = 240;
    }
    
    self.myView.qmui_height -= buttonHeight;
    
    _ewhView.frame = CGRectMake(10, margin, self.myView.qmui_width - 20, wehHeight);
    
    _separatorLayer.frame = CGRectMake(self.myView.qmui_width / 2 - PixelOne, self.myView.qmui_height - dayHeight - margin, 2, dayHeight);
    _monthTitleLabel.frame = CGRectMake(0, _separatorLayer.frame.origin.y, self.myView.qmui_width / 2, monthHeight);
    _dayTitleLabel.frame = CGRectMake(self.myView.qmui_width / 2, _monthTitleLabel.qmui_top, _monthTitleLabel.qmui_width, _monthTitleLabel.qmui_height);
    
    _monthLabel.frame = CGRectMake(0, _monthTitleLabel.qmui_bottom, self.myView.qmui_width / 2, dayHeight - monthHeight);
    [_monthLabel sizeToFit];
    _monthLabel.qmui_left = self.myView.qmui_width / 4 - _monthLabel.qmui_width / 2;
    _monthUnitLabel.qmui_left = _monthLabel.qmui_right;
    _monthUnitLabel.qmui_bottom = _monthLabel.qmui_bottom;
    
    _dayLabel.frame = CGRectMake(self.myView.qmui_width / 2, _monthTitleLabel.qmui_bottom, self.myView.qmui_width / 2, dayHeight - monthHeight);
    [_dayLabel sizeToFit];
    _dayLabel.qmui_left = 3 * self.myView.qmui_width / 4 - _dayLabel.qmui_width / 2;
    _dayUnitLabel.qmui_left = _dayLabel.qmui_right;
    _dayUnitLabel.qmui_bottom = _dayLabel.qmui_bottom;
    
    CGFloat tmp = (_ewhView.qmui_bottom + _separatorLayer.frame.origin.y) / 2.0f;
    _timingLabel1.frame = CGRectMake(20, tmp - 30, self.myView.qmui_width - 40, 30);
    _timingLabel2.frame = CGRectMake(20, tmp, self.myView.qmui_width - 40, 30);
    if (!_timingLabel1.hidden && _timingLabel2.hidden) {
        _timingLabel1.qmui_top += 15;
    } else if (_timingLabel1.hidden && !_timingLabel2.hidden) {
        _timingLabel2.qmui_top -= 15;
    }
    
    CGFloat btn_width = self.myView.qmui_width / 5.0f;
    _economyBtn.frame = CGRectMake(self.myView.qmui_left, self.myView.qmui_bottom + buttonMargin, btn_width, buttonHeight - 2 * buttonMargin);
    _fastBtn.frame = CGRectOffset(_economyBtn.frame, btn_width, 0);
    _powerBtn.frame = CGRectOffset(_fastBtn.frame, btn_width, 0);
    _clockBtn.frame = CGRectOffset(_powerBtn.frame, btn_width, 0);
    _deinfectionBtn.frame = CGRectOffset(_clockBtn.frame, btn_width, 0);
}

-(void)refresh {
    self.title = _model.device_nick_name;
    
    if (_ewhView.ctrlState < 2) {
        _ewhView.maxTemp = [_model floatWithCode:MAX_TEMP];
        _ewhView.minTemp = [_model floatWithCode:MIN_TEMP];
        _ewhView.currentTemp = [_model floatWithCode:CURRENT_TEMP];
        _ewhView.setTemp = [_model floatWithCode:TARGET_TEMP];
    }
    
    NSInteger on1 = [_model intWithCode:TIMER1_ON];
    NSInteger off1 = [_model intWithCode:TIMER1_OFF];
    if (off1 - on1 == 240 || on1 - off1 == 1200) {
        NSString *str = [NSString stringWithFormat:@"%02d:%02d - %02d:%02d", (int)on1 / 60, (int)on1 % 60, (int)off1 / 60, (int)off1 % 60];
        _timingLabel1.hidden = NO;
        _timingLabel1.text = [NSString stringWithFormat:@"%@ %@",NSLocalizedString(@"appointment_timing", nil), str];
    } else {
        _timingLabel1.hidden = YES;
    }
    
    NSInteger on2 = [_model intWithCode:TIMER2_ON];
    NSInteger off2 = [_model intWithCode:TIMER2_OFF];
    if (off2 - on2 == 240 || on2 - off2 == 1200) {
        NSString *str = [NSString stringWithFormat:@"%02d:%02d - %02d:%02d", (int)on2 / 60, (int)on2 % 60, (int)off2 / 60, (int)off2 % 60];
        _timingLabel2.hidden = NO;
        _timingLabel2.text = [NSString stringWithFormat:@"%@ %@",NSLocalizedString(@"appointment_timing", nil), str];
    } else {
        _timingLabel2.hidden = YES;
    }
    
    int totalTime = (int)[_model intWithCode:TOTALTIME];
    _dayLabel.text = [NSString stringWithFormat:@"%d",totalTime];
    if (totalTime >= 1000) {
        [self showServiceAlert];
    }
    
    NSInteger power = [_model intWithCode:POWER] & 0x0001;
    _powerBtn.selected = power;
    _economyBtn.enabled = power;
    _fastBtn.enabled = power;
    _clockBtn.enabled = power;
    _deinfectionBtn.enabled = power;
    
    if (power) {
        NSInteger mode = [_model intWithCode:MODE];
        if (mode == 0) {
            _economyBtn.selected = YES;
            _fastBtn.selected = NO;
        } else {
            _economyBtn.selected = NO;
            _fastBtn.selected = YES;
        }
        _deinfectionBtn.selected = [_model intWithCode:DEINFECT];
        _clockBtn.selected = !(_timingLabel1.hidden && _timingLabel2.hidden);
    }
    
    [self.view setNeedsLayout];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [self refresh];
    
    //获取一次设备状态信息
    _model.needDetail = YES;
    [_model fireTimer];
    
    WS(ws);
    [_model getElectricityTwoMonth:^(BOOL success) {
        if (success) {
            ws.monthLabel.text = [NSString stringWithFormat:@"%.1f", [ws.model totalElectThisMonth]];
            [ws.view setNeedsLayout];
        }
    }];
    
    self.navigationController.interactivePopGestureRecognizer.delaysTouchesBegan = NO;
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    self.navigationController.interactivePopGestureRecognizer.delaysTouchesBegan = YES;
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    
    _model.needDetail = NO;
}

-(void)statusChanged:(NSNotification *)notification {
    PHDevice *model = (PHDevice *)notification.object;
    if (model == _model) {
        [self refresh];
    }
}

#pragma mark - EWHViewDelegate
-(void)targetTempWillChange:(EWHView *)whview {
    [self.model fireTimer];
}

-(void)whView:(EWHView *)whview targetTempChanged:(float)targetTemp {
    WS(ws);
    [_model modify:@{ TARGET_TEMP: @(targetTemp) } animated:YES finish:^(BOOL success) {
        if (success) {
            [ws.model fireTimer];
        }
    }];
}

-(void)economyAction:(id)sender {
    WS(ws);
    [_model modify:@{ MODE: @0 } animated:YES finish:^(BOOL success) {
        if (success) {
            [KKHUD showSucceed:NSLocalizedString(@"tips_switch_mode_eco", nil)];
            
            [ws.model fireTimer];
        }
    }];
}

-(void)fastAction:(id)sender {
    WS(ws);
    [_model modify:@{ MODE: @1 } animated:YES finish:^(BOOL success) {
        if (success) {
            [KKHUD showSucceed:NSLocalizedString(@"tips_switch_mode_fast_hot", nil)];
            
            [ws.model fireTimer];
        }
    }];
}

-(void)powerAction:(id)sender {
    WS(ws);
    NSInteger value = !_powerBtn.isSelected;
    [_model modify:@{ POWER: @(value) } animated:YES finish:^(BOOL success) {
        if (success) {
            [ws.model fireTimer];
        }
    }];
}

-(void)clockAction:(id)sender {
    PHTimingViewController *timingVC = [[PHTimingViewController alloc] initWithDeviceModel:_model];
    [self.navigationController pushViewController:timingVC animated:YES];
}

-(void)deinfectionAction:(id)sender {
    WS(ws);
    NSInteger value = !_deinfectionBtn.isSelected;
    [_model modify:@{ DEINFECT: @(value) } animated:YES finish:^(BOOL success) {
        if (success) {
            if (value) {
                [KKHUD showSucceed:NSLocalizedString(@"tips_turn_on_deinfection", nil)];
            } else {
                [KKHUD showSucceed:NSLocalizedString(@"tips_turn_off_deinfection", nil)];
            }
            
            [ws.model fireTimer];
        }
    }];
}

- (void)setupNavigationItems {
    
    self.title = _model.device_nick_name;
    self.navRightImage = UIImageMake(@"icon_menu");
    
    [super setupNavigationItems];
}

-(void)rightAction {
    
    WS(ws);
    QMUIPopupMenuView *popupView = [[QMUIPopupMenuView alloc] init];
    popupView.automaticallyHidesWhenUserTap = YES;
    popupView.maximumWidth = 180;
    popupView.shouldShowItemSeparator = YES;
    popupView.separatorInset = UIEdgeInsetsMake(0, popupView.padding.left, 0, popupView.padding.right);
    
    UIImage *image1 = [UIImageMake(@"icon_edit") imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
    QMUIPopupMenuItem *item1 = [QMUIPopupMenuItem itemWithImage:image1 title:NSLocalizedString(@"title_edit_name", nil) handler:^{
        [popupView hideWithAnimated:YES];
        
        [KKAlert inputWithTitle:NSLocalizedString(@"title_edit_name", nil) text:ws.model.device_nick_name placeholder:NSLocalizedString(@"tips_input_name", nil) ok:^(NSString *string) {
            [ws.model modifyNickname:string finish:^(BOOL success) {
                if (success) {
                    ws.title = string;
                    ws.model.device_nick_name = string;
                }
            }];
        }];
    }];
    
    UIImage *image2 = [UIImageMake(@"icon_statistics") imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
    QMUIPopupMenuItem *item2 = [QMUIPopupMenuItem itemWithImage:image2 title:NSLocalizedString(@"title_cost_statistics", nil) handler:^{
        [popupView hideWithAnimated:YES];
        
        PHElectricityViewController *electricityVC = [[PHElectricityViewController alloc] initWithDeviceModel:ws.model];
        [ws.navigationController pushViewController:electricityVC animated:YES];
        
    }];
    popupView.items = @[ item1, item2 ];
    [popupView layoutWithTargetRectInScreenCoordinate:CGRectMake(SCREEN_WIDTH - 30, self.qmui_navigationBarMaxYInViewCoordinator, 1, 1)];
    [popupView showWithAnimated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

@end
